const router = require("express").Router();
const assert = require("http-assert");
const { Article } = require("../models");

// 获取文章列表
router.get("/", async (req, res) => {
  const { page = 1, page_size = 20 } = req.query;
  const { count, rows } = await Article.findAndCountAll({
    offset: page_size * (page - 1),
    limit: Number(page_size),
  });

  return res.send({ count, rows });
});

// 获取文章详情
router.get("/:id", async (req, res) => {
  const data = await Article.findByPk(req.params.id);
  assert(data, 404, "数据未找到");
  res.send(data);
});

// 创建文章
router.post("/", (req, res) => {
  const { title, content } = req.body;
  if (!title || title.length === 0 || title.length > 60) {
    assert(title, 401, "请正确填写文章标题");
  }
  assert(content, 401, "请填写文章内容");
  Article.create({ title, content })
    .then(() => res.send({ code: 0 }))
    .catch(() => res.send({ code: 1 }));
});

// 删除文章
router.delete("/:id", (req, res) => {
  Article.destroy({ where: { id: req.params.id } })
    .then(() => res.send({ code: 0 }))
    .catch(() => res.send({ code: 1 }));
});

// 修改文章
router.patch("/:id", async (req, res) => {
  const { title, content } = req.body;
  assert(title || content, 401, "请填写需要修改的内容");

  const data = {};
  if (title && title.length < 60) {
    data.title = title;
  }
  if (content) {
    data.content = content;
  }

  Article.update(data, { where: { id: req.params.id } })
    .then(() => res.send({ code: 0 }))
    .catch(() => res.send({ code: 1 }));
});

module.exports = router;
